﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using Granite.Modeling;
using Granite.Modeling.Validators;

namespace LeadTracker.Entities
{
	public class Lead : ChangeTrackingModelBase
	{
		readonly LeadCommentCollection m_Comments = new LeadCommentCollection();

		public Lead()
		{
			CreatedDate = DateTimeOffset.Now;
			IsNew = true;
			Checkpoint();
		}

		public Lead(IDictionary<string, object> fields)
		{
			Load(fields);
		}

		public bool IsNew
		{
			get { return GetOrDefault<bool>("IsNew"); }
			set { SetValue("IsNew", value); }
		}

		public int LeadKey
		{
			get { return GetOrDefault<int>("LeadKey"); }
			set { SetValue("LeadKey", value); }
		}

		[Required]
		[MaxLength(127)]
		public string Title
		{
			get { return GetOrDefault<string>("Title"); }
			set { SetValue("Title", value); }
		}

		public int? OwnerKey
		{
			get { return GetOrDefault<int?>("OwnerKey"); }
			set { SetValue("OwnerKey", value); }
		}

		[Required]
		public int? CreatedByKey
		{
			get { return GetOrDefault<int?>("CreatedByKey"); }
			set { SetValue("CreatedByKey", value); }
		}

		public DateTimeOffset? CreatedDate
		{
			get { return GetOrDefault<DateTimeOffset?>("CreatedDate"); }
			set { SetValue("CreatedDate", value); }
		}

		[Required]
		public LeadType LeadType
		{
			get { return GetOrDefault<LeadType>("LeadType", LeadType.RawLead); }
			set { SetValue("LeadType", value); }
		}

		[Required]
		public LeadStatus LeadStatus
		{
			get { return GetOrDefault<LeadStatus>("LeadStatus", LeadStatus.Proposed); }
			set { SetValue("LeadStatus", value); }
		}

		/// <summary>
		/// This is set to true when comments have been loaded from the database.
		/// </summary>
		public bool CommentsLoaded
		{
			get { return GetOrDefault<bool>("CommentsLoaded", false); }
			private set { SetValue("CommentsLoaded", value); }
		}

		public void LoadComments(IEnumerable<IDictionary<string, object>> table)
		{
			Comments.Load(table);
			CommentsLoaded = true;
		}

		public LeadCommentCollection Comments
		{
			get { return m_Comments; }
		}

	}
}
